package com.base.common.http.handler;

import android.util.Log;


import com.base.common.http.constant.SocketConstant;
import com.base.common.http.model.DownLoadModel;
import com.base.common.http.model.HttpConfigModel;
import com.base.common.http.util.CloseUtils;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;

import static com.yf.cmw.constant.BussConstant.TEMP_FILE_PREFIX;

public class FileSocketHandler extends SocketAdapterHandler {

    private static final String TAG = "FileSocketHandler";

    private Socket socket;

    private HttpConfigModel httpConfig;

    private CompleteCallback callback;

    public FileSocketHandler(Socket socket, HttpConfigModel httpConfig, CompleteCallback callback) {
        super();
        this.socket = socket;
        this.httpConfig = httpConfig;
        this.callback = callback;
    }


    @Override
    public void run() {
        super.run();
        int bufferSize = 2048;
        byte[] buffer = new byte[bufferSize];
        DataInputStream dataInputStream = null;
        FileOutputStream fos = null;
        try {
            dataInputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            String fileName = dataInputStream.readUTF();
            DownLoadModel downLoadModel = createModel(dataInputStream);
            String sourceFileName = downLoadModel.getSourceFileName();
            long fileLength = downLoadModel.getFileSize();
            if(!isEmpty(sourceFileName)) fileName = sourceFileName;
            Log.i(TAG,String.format("客户端文件名：%s, 文件长度:%d", fileName, fileLength));
            String filePath = httpConfig.getHomeDir() + fileName+TEMP_FILE_PREFIX;
            System.out.println(filePath);
            File file = new File(filePath);
            Log.i(TAG,String.format("开始写入文件：%s", file.getAbsolutePath()));
            file.getParentFile().mkdirs();  // 修复文件目录找不到
            if(!file.exists()){
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            int len = 0;
            long totlalLen = 0;
            while ((len = dataInputStream.read(buffer,0,bufferSize)) != -1){
                fos.write(buffer, 0, len);
                fos.flush();
                totlalLen += len;
                Log.i(TAG,String.format("文件总长度：%d , 当前写入的长度:%d ", fileLength, totlalLen));
            }
            String lpath = file.getAbsolutePath();
            lpath = lpath.replace(TEMP_FILE_PREFIX,"");
            File newFile = new File(lpath);
            file.renameTo(newFile);
            downLoadModel.setLpath(newFile.getAbsolutePath());
            if(null != callback) callback.completed(downLoadModel);
            Log.i(TAG,String.format("文件：%s 写入成功", newFile.getAbsolutePath()));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            CloseUtils.close(fos);
           this.close();
        }
    }

    private DownLoadModel createModel( DataInputStream dataInputStream) throws IOException {
        long fileLength = dataInputStream.readLong();
        Long sourceId = dataInputStream.readLong();
        String aname = dataInputStream.readUTF();
        String sourceFileName = dataInputStream.readUTF();
        String address = dataInputStream.readUTF();
        DownLoadModel model = new DownLoadModel();
        model.setSourceId(sourceId);
        model.setAname(aname);
        model.setSourceFileName(sourceFileName);
        model.setFileSize(fileLength);
        model.setAddress(address);
        return model;
    }



    @Override
    int getType() {
        return SocketConstant.SOCKET_HANDLER_TYPE_FILE;
    }

    @Override
    public void close()  {
        CloseUtils.close(socket);
        socket = null;
    }
}
